<template>
  <el-dialog :title="!dataForm.id ? '调价新增':'调价修改'" :close-on-click-modal="false" :visible.sync="visible" center
    fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form inline :model="dataForm" :rules="dataRule" ref="dataForm">
      <el-row>
        <el-col :span="6">
          <el-form-item label="促销活动名称" prop="promotionTitle" label-width="100px">
            <el-input v-model="dataForm.promotionTitle" placeholder="促销活动名称" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="dataForm.createTime" placeholder="创建时间" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生效时间" prop="startTime">
            <el-input v-model="dataForm.startTime" placeholder="生效时间" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="截至时间" prop="endTime">
            <el-input v-model="dataForm.endTime" placeholder="截至时间" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="价格组选择" prop="groupList">
        <el-select v-model="dataForm.priceGroupId " @change="groupSelectChange($event)" disabled>
          <el-option v-for="item in groupOptions" :key="item.id" :label="item.groupName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      
    </el-form>
    <el-form label-width="40px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="查询部门">
            <el-input type="textarea" v-model="dataForm.deptName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="memo">
        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo" disabled></el-input>
      </el-form-item>
    </el-form>
    
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="addBrand">选择品种</el-button>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button type="danger" @click="delTableData">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" ref="multipleTable" border v-loading="dataListLoading" header-cell-class-name="miui-header-cell-style" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="品种代码"></el-table-column>
      <el-table-column prop="brandName" label="品种名称"></el-table-column>
      <el-table-column prop="supplyName" label="所属制造商"></el-table-column>
      <!-- <el-table-column prop="spec" label="型号"></el-table-column> -->
      <el-table-column prop="originalPrice" label="现销售价格"> </el-table-column>
      <el-table-column prop="promotionPrice" label="调整价格">
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
    </span>
    <!-- 弹窗, 品种价格等选择 -->
    <search-brand v-if="brandInfoVisible" ref="brandInfo" @updateForm="getInfoData"></search-brand>
    <search-dept v-if="deptVisible" ref="deptDialog" @refreshData="getDeptData"></search-dept>
  </el-dialog>
</template>

<script>
  import {mapGetters} from 'vuex'
  import { filterParams } from "@/util/tools";
  import { getEimsPromotionObj, addEimsPromotionObj, putEimsPromotionObj } from '@/api/eims/promotion'
  import { getGroupList } from "@/api/eims/price-group";
  import { getObj } from "@/api/admin/dept"
  import { getPriceGroupByDeptId } from "@/api/eims/price-group"
  import { getCtgList } from "@/api/eims/ctg";
  // import GoodsList from "@/components/business/goods-search-single";
  import SearchDept from './SearchDept'
  import SearchBrand from "./SearchBrandSpecPrice";

  export default {
    data() {
      return {
		    ischeck: false,
        visible: false,
        deptVisible: false,
        deptDialog: false,
        priceFlag: '',
        dataForm: {
          id: 0,
          promotionTitle: '',
          startTime: '',
          endTime: '',
          auditStatus: 0,
          auditUser: '',
          stopTime: '',
          stopUser: '',
          memo: '',
          deptName: '',
          depts: [],
          details: []
        },
        ctgOptions: [],
        groupOptions: [],
        dataList: [],
        dataListLoading: false,
        dataRule: {
          priceGroupId: [{
            required: true,
            message: "请选择价格组"
          }],
          promotionTitle: [{
            required: true,
            message: '促销活动名称不能为空',
            trigger: 'blur'
          }],
          startTime: [{
            required: true,
            message: '生效时间不能为空',
            trigger: 'blur'
          }],
          endTime: [{
            required: true,
            message: '结束时间不能为空',
            trigger: 'blur'
          }],
          auditStatus: [{
            required: true,
            message: '审核状态(1-已审核,0-未审核)不能为空',
            trigger: 'blur'
          }]
        },
        brandInfoVisible: false,
        selectionList: [],

      };
    },
    components: {
      SearchBrand,
      SearchDept
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      init(id) {
        this.getGroupList();
        this.getGoodsCtgList();
        this.getDate();
        this.getPriceGroupId();

        this.dataList = [];

        this.dataForm.id = id || 0
        if (!this.dataForm.id) {
          this.timeFormate(new Date());
          this.dataForm.deptName = ''
          this.dataForm.depts = []
          this.dataForm.details = []
        }

        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getEimsPromotionObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = response.data.data.details
                this.dataForm.depts = response.data.data.depts
                let names = []
                this.dataForm.depts.forEach(item => {
                    names.push(item.deptName)
                })
                this.$set(this.dataForm,'deptName', names.join(','))
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      //显示当前时间（年月日时分秒）
      timeFormate(timeStamp) {
        let year = new Date(timeStamp).getFullYear();
        let month = new Date(timeStamp).getMonth() + 1 < 10 ? "0" + (new Date(timeStamp).getMonth() + 1) : new Date(timeStamp).getMonth() + 1;
        let date = new Date(timeStamp).getDate() < 10 ? "0" + new Date(timeStamp).getDate() : new Date(timeStamp).getDate();
        let hh = new Date(timeStamp).getHours() < 10 ? "0" + new Date(timeStamp).getHours() : new Date(timeStamp).getHours();
        let mm = new Date(timeStamp).getMinutes() < 10 ? "0" + new Date(timeStamp).getMinutes() : new Date(timeStamp).getMinutes();
        let ss = new Date(timeStamp).getSeconds() < 10 ? "0" + new Date(timeStamp).getSeconds() : new Date(timeStamp).getSeconds();
        this.nowTime = "POUT" + year + "" + month + "" + date + "" + hh + "" + mm + "" + ss + this.dataForm.deptId;
        this.dataForm.createTime = year + "-" + month + "-" + date;
      },
      // 商品类别改变时获取名字
      groupSelectChange($event) {
        this.groupOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.groupName = item.groupName;
          }
        });
      },
            //根据当前部门判断是否能调整所有价格组价格
      getPriceGroupFlag(){
        getObj(this.userInfo.lessDeptId).then(response =>{
          if(response.data.code == '0'){
            this.priceFlag = response.data.data.priceFlag
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //根据当前部门获取价格组id
      getPriceGroupId(){
        getPriceGroupByDeptId(this.userInfo.lessDeptId).then(response =>{
          if(response.data.code == '0'){
            this.dataForm.priceGroupId = response.data.data.groupId
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 打开商品列表弹窗
      addGoodsBySingle() {
        if (!this.dataForm.priceGroupId) {
          this.$message.warning("请选择价格组");
          return;
        }
        let params = {
          priceGroupId: this.dataForm.priceGroupId
        };
        let data = {
          params: params,
          data: this.dataList
        };
        this.goodsVisible = true;
        this.$nextTick(() => {
          this.$refs.goodsDialog.init(data);
        });
      },
      //  打开查询部门弹窗
      openDeptDialog() {
        this.deptVisible = true
        this.$nextTick(() => {
          this.$refs.deptDialog.init(this.dataForm.priceGroupId)
        })
      },
      //  获取选择部门数据
      getDeptData(data) {
        this.dataForm.depts = []
        let names = []
        if (data.length) {
          data.forEach(item => {
            let info= {
              deptId : item.id,
              deptName : item.name
            }
            names.push(item.name)
            this.dataForm.depts.push(info)
          })
        }
        this.$set(this.dataForm,'deptName', names.join(','))
      },
      
      handleSelectionChange(val) {
        this.selectionList = val;
      },
      // 删除选中的商品
      delTableData() {
        let arrList = this.selectionList.map(x => {
            return {
                brandId: x.brandId,
                spec: x.spec,
                price: x.price
            }
        });
        for(let i = 0; i < arrList.length;i++){
            this.dataList = this.dataList.filter(x => {
                return (x.brandId != arrList[i].brandId || x.spec != arrList[i].spec || x.price != arrList[i].price)
            })
        }
        this.$refs.multipleTable.clearSelection();
      },
      // 表单提交
      dataFormSubmit() {
        if(this.dataList.length<=0){
          this.$message.warning("请先选择商品")
        }
        for(let i=0;i<this.dataList.length;i++){
          if(!this.dataList[i].promotionPrice){
            this.$message.warning("请先填写调整价格!")
            return
          }
        }
        this.dataForm.details = this.dataList
				this.dataForm.createTime = ""
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              putEimsPromotionObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              })
            } else {
              addEimsPromotionObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              })
            }
          }
        })
        
      },

      /*
       * *  获取价格组列表
       */
      getGroupList() {
        getGroupList().then(result => {
          this.groupOptions = result.data.data;
        });
      },
      //  获取商品类别列表
      getGoodsCtgList() {
        getCtgList().then(result => {
          this.ctgOptions = result.data.data;
        });
      },
      //  商品类别改变事件
      ctgChange(val) {
        this.dataForm.supplyId = "";
        this.dataForm.supplyName = "";
      },
      //  选择制造商
      choiceSupply() {
        let data = {
          ctgId: this.dataForm.ctgId
        };
        this.supplyVisible = true;
        this.$nextTick(() => {
          this.$refs.supplyDialog.init(data);
        });
      },
      //  获取制造商信息
      getSupplyData(data) {
        this.dataForm.supplyId = data.id;
        this.dataForm.supplyName = data.name;
      },
      //获取当前日期
      getDate() {
        let nowDate = new Date();
        let sysTime = {
            year: nowDate.getFullYear(),
            month: (nowDate.getMonth() + 1) < 10 ? "0" +(nowDate.getMonth() + 1) : (nowDate.getMonth() + 1),
            date: nowDate.getDate() < 10 ? "0" +nowDate.getDate() : nowDate.getDate(),
        }
        this.dataForm.createTime = sysTime.year + '-' + sysTime.month + '-'  + sysTime.date;
      },
      //打开弹窗
      addBrand(){
        this.brandInfoVisible = true;
        this.$nextTick(() => {
          let data ={
            priceGroupId :this.dataForm.priceGroupId,
            dataList : this.dataList
          }
          this.$refs.brandInfo.init(data);
        });
      },
      //  获取品种等信息
      getInfoData(data) {
        let list = [];
        data.forEach(item => {
          item.ctgId = item.ctgId;
          item.brandName = item.brandName;
          item.goodsCode = item.code;
          item.originalPrice = item.price;
          item.supplyId = item.supplyId;
          item.spec = item.spec;
          list.push(item);
        });
        this.dataList = JSON.parse(JSON.stringify(data));
        this.dataForm.detailList = list;
      },
    }
  };
</script>
